package com.xzsoft.gdwz.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class HttpClientUtil {
	// static Logger logger = Logger.getLogger(HttpClientUtil.class);
	public static String httpGet(String url) {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse resp = client.execute(httpGet);
			HttpEntity entity = resp.getEntity();
			String respContent = EntityUtils.toString(entity, "UTF-8").trim();
			httpGet.abort();
			client.getConnectionManager().shutdown();
			return respContent;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			client.getConnectionManager().shutdown();
		}
	}

	public static HttpClient httpGetLogin(String url) {
		HttpClient client = new DefaultHttpClient();
		HttpClientParams.setCookiePolicy(client.getParams(),
				CookiePolicy.BROWSER_COMPATIBILITY);
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse resp = client.execute(httpGet);
			HttpEntity entity = resp.getEntity();
			String respContent = EntityUtils.toString(entity, "UTF-8").trim();
			return client;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static HttpPost httpLogin(String url, Map<String, String> params) {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(
					params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				NameValuePair nameValuePair = new BasicNameValuePair(
						entry.getKey(), String.valueOf(entry.getValue()));
				valuePairs.add(nameValuePair);
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					valuePairs, "UTF-8");
			httpPost.setEntity(formEntity);
			HttpResponse resp = client.execute(httpPost);
			HttpEntity entity = resp.getEntity();
			String respContent = EntityUtils.toString(entity, "UTF-8").trim();

			CookieStore cookieStore = ((AbstractHttpClient) client)
					.getCookieStore();
			httpPost.abort();
			httpPost.releaseConnection();
			return httpPost;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String httpPost(String url, Map<String, String> params,
			CookieStore cookieStore) {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(
					params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				NameValuePair nameValuePair = new BasicNameValuePair(
						entry.getKey(), String.valueOf(entry.getValue()));
				valuePairs.add(nameValuePair);
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					valuePairs, "UTF-8");
			httpPost.setEntity(formEntity);
			((AbstractHttpClient) client).setCookieStore(cookieStore);
			HttpResponse resp = client.execute(httpPost);
			HttpEntity entity = resp.getEntity();
			String respContent = EntityUtils.toString(entity, "UTF-8").trim();
			httpPost.abort();
			client.getConnectionManager().shutdown();
			return respContent;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			client.getConnectionManager().shutdown();
		}
	}

	public static String httpPost(String url, Map<String, String> params) {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(
					params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				NameValuePair nameValuePair = new BasicNameValuePair(
						entry.getKey(), String.valueOf(entry.getValue()));
				valuePairs.add(nameValuePair);
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					valuePairs, "UTF-8");
			httpPost.setEntity(formEntity);
			HttpResponse resp = client.execute(httpPost);
			HttpEntity entity = resp.getEntity();
			String respContent = EntityUtils.toString(entity, "UTF-8").trim();
			httpPost.abort();
			client.getConnectionManager().shutdown();
			return respContent;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			client.getConnectionManager().shutdown();
		}
	}

	public static String httpPost(String url, String params) {
		int status;
		String body = null;
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-type", "application/json; charset=utf-8");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
		try {
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				status = 1;
				return null;
			}
			// Read the response body
			body = EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return body;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		
		

//		String user_id = "d25320d6-140b-458b-b73f-61c6305a5bf0";
//		String loginUrl2 = "http://219.142.82.140:8090/gdxj/platformAction.do?method=personalLogin&loginName=SUNSHULI&password=7c087b3601f51fbed2b824c9436998c1";
//		String uploadUrl = "http://219.142.82.140:8090/gdxj/xipAttMrgAction.do?method=upload&src_id=de7b3b11-2761-48cb-8686-df0998aaa8c3&attCatCode=JGTJFJ&bus_no=JGTJFJ&userId=d25320d6-140b-458b-b73f-61c6305a5bf0";
//		String filename = "爱你.txt";
//		HttpClientUtil
//				.uploadFile(loginUrl2, uploadUrl, filename, "D:/worksoft");

		// Map<String, String> map = new HashMap<String, String>();
		// String url = "https://bizapi.jd.com/oauth2/accessToken";
		// String grant_type = "access_token";
		// String client_id = "guodian";
		// String client_secret = "1ZKMXxre3XVykhdHk0eL";
		// String timestamp = new DateTime().toString("yyyy-MM-ddHH:mm:ss");
		// String password = HttpClientUtil.stringMD5("gdwl2016.");
		// String username = "国电物流有限公司";
		// String scope = "";
		// String sign = client_secret+timestamp+client_id+username+password
		// +grant_type+scope+client_secret;
		// System.out.println("加密前："+sign);
		// sign = HttpClientUtil.stringMD5(sign).toUpperCase();
		// System.out.println("加密后："+sign);
		// map.put("grant_type", grant_type);
		// map.put("client_id", client_id);
		// map.put("client_secret", client_secret);
		// map.put("timestamp",timestamp);
		// map.put("username", username);
		// map.put("password", password);
		// map.put("scope", scope);
		// map.put("sign", sign);
		// System.out.println(JSONObject.fromObject(map).toString());
		// String result = HttpClientUtil.httpPost(url, map);
		// System.out.println("获取token结果："+result);
		// JSONObject jsonObject = JSONObject.fromObject(result);
		// boolean success = (Boolean)jsonObject.get("success");

	}

	public static String stringMD5(String pw) {
		try {
			// 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 输入的字符串转换成字节数组 ,强制用utf-8转码
			byte[] inputByteArray = pw.getBytes("utf-8");
			// inputByteArray是输入字符串转换得到的字节数组
			messageDigest.update(inputByteArray);
			// 转换并返回结果，也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 字符数组转换成字符串返回
			return byteArrayToHex(resultByteArray);
		} catch (Exception e) {
			return null;
		}
	}

	public static String stringSHA1(String pw) {
		try {
			// 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
			// 输入的字符串转换成字节数组 ,强制用utf-8转码
			byte[] inputByteArray = pw.getBytes("utf-8");
			// inputByteArray是输入字符串转换得到的字节数组
			messageDigest.update(inputByteArray);
			// 转换并返回结果，也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 字符数组转换成字符串返回
			return byteArrayToHex(resultByteArray);
		} catch (Exception e) {
			return null;
		}
	}

	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String byteArrayToHex(byte[] byteArray) {

		// 首先初始化一个字符数组，用来存放每个16进制字符
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}

	/*
	 * 根据url下载文件，保存到filepath中
	 * 
	 * @param url
	 * 
	 * @param filepath
	 * 
	 * @return
	 */
	public static String download(String loginUrl, String url, String filepath) {
		try {
			@SuppressWarnings("deprecation")
			HttpClient client = null;
			if (loginUrl != null && !"".equals(loginUrl)) {
				client = httpGetLogin(loginUrl);
			} else {
				client = new DefaultHttpClient();
			}
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = client.execute(httpget);
			HttpEntity entity = response.getEntity();
			System.out.println("内容编码是：" + entity.getContentEncoding());
			System.out.println("内容类型是：" + entity.getContentType());
			InputStream is = entity.getContent();
			String fileName = getFileName(response, url);
			File file = new File(filepath + File.separator + fileName);
			file.getParentFile().mkdirs();
			OutputStream out = new FileOutputStream(file);
			byte[] buffer = new byte[4096];
			int ch = 0;
			while ((ch = is.read(buffer)) > 0) {
				// out.write(buffer,0,ch);
				byte[] bytes = new byte[ch];
				System.arraycopy(buffer, 0, bytes, 0, ch);
				out.write(bytes);

			}
			is.close();
			out.flush();
			out.close();
			httpget.abort();
			client.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 获取response header中Content-Disposition中的filename值
	 * 
	 * @param response
	 * 
	 * @return
	 */
	public static String getFileName(HttpResponse response, String url) {
		Header contentHeader = response.getFirstHeader("Content-Disposition");
		String filename = null;
		if (contentHeader != null) {
			HeaderElement[] values = contentHeader.getElements();
			if (values.length == 1) {
				NameValuePair param = values[0].getParameterByName("filename");
				if (param != null) {
					try {
						filename = new String(param.getValue().toString()
								.getBytes(), "utf-8");
						filename = URLDecoder.decode(param.getValue(), "utf-8");
						filename = param.getValue();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		if (filename == null) {
			filename = url.substring(url.lastIndexOf("/") + 1);
		}
		return filename;
	}

	public static void getFile(String loginUrl, String url, String fileName) {
		@SuppressWarnings("deprecation")
		HttpClient httpClient = null;
		if (loginUrl != null) {
			httpClient = httpGetLogin(loginUrl);
		} else {
			httpClient = new DefaultHttpClient();
		}
		HttpGet httpget = new HttpGet(url);
		try {
			ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
				public byte[] handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						return EntityUtils.toByteArray(entity);
					} else {
						return null;
					}
				}
			};

			byte[] charts = httpClient.execute(httpget, handler);
			FileOutputStream out = new FileOutputStream(fileName);
			out.write(charts);
			out.close();
			httpget.abort();
			httpClient.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 文件上传
	 * 
	 * @param url
	 * @param filename1
	 * @param filename2
	 * @param filepath
	 */
	public static void uploadFile1(String loginUrl, String url, String filename,
			String filepath) {
		HttpClient httpClient = new DefaultHttpClient();
		filename = filepath + File.separator + filename;
		HttpPost httppost = new HttpPost(url);

		 if (loginUrl != null && !"".equals(loginUrl)) {
			httpClient = httpGetLogin(loginUrl);
		}
		try {
			HttpParams params = httpClient.getParams();
			params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
					Charset.forName("UTF-8"));
			FileBody bin = new FileBody(new File(filename));
			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart("file1", bin);
			httppost.setEntity(reqEntity);
			// httppost.setHeader("Content-Type", "multipart/form-data");
			HttpResponse response = httpClient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				System.out.println("服务器正常响应.....");
				HttpEntity resEntity = response.getEntity();
				System.out.println(EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据
				System.out.println(resEntity.getContent());
				EntityUtils.consume(resEntity);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.getConnectionManager().shutdown();
			} catch (Exception ignore) {

			}
		}
	}
	
	public static void uploadFile(String loginUrl, String url, String filename, String filepath){
		ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);      
		HttpClient httpClient = null;
		if (loginUrl != null && !"".equals(loginUrl)) {
			httpClient = httpGetLogin(loginUrl);
		}
		HttpPost httppost = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
		File file = new File(filepath + File.separator + filename);
		builder.addBinaryBody("uploadfile", file);
		StringBody stringBody=new StringBody("中文乱码",contentType);
		builder.addPart("test", stringBody);
		HttpEntity entity = builder.build();// 生成 HTTP POST 实体  	
		httppost.setEntity(entity);//设置请求参数
		try {
			HttpResponse response = httpClient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				System.out.println("服务器正常响应.....");
				HttpEntity resEntity = response.getEntity();
				System.out.println(EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据
				System.out.println(resEntity.getContent());
				EntityUtils.consume(resEntity);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				httpClient.getConnectionManager().shutdown();
			} catch (Exception ignore) {

			}
		}
	}


	@Test
	public void test() {
		download(
				null,
				"http://4493bz.1985t.com/uploads/allimg/150127/4-15012G52133.jpg",
				"e:/");
	}

}
